package block.chain.controller;

import block.chain.cache.BlockCache;
import block.chain.service.BlockService;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @Author: xx
 * @CreateTime : 2025/6/10 15:34
 */
@Controller
public class BlockController {

    @Resource
    BlockService blockService;

    @Resource
    BlockCache blockCache;

    /**
     * 查看当前节点区块链数据
     *
     * @return
     */
    @GetMapping("/scan")
    @ResponseBody
    public String scanBlock() {
        return JSON.toJSONString(blockCache.getBlockChain());
    }

    /**
     * 查看当前节点区块链数据
     *
     * @return
     */
    @GetMapping("/data")
    @ResponseBody
    public String scanData() {
        return JSON.toJSONString(blockCache.getPackedTransactions());
    }

    /**
     * 创建创世区块
     *
     * @return
     */
    @GetMapping("/init")
    @ResponseBody
    public String createFirstBlock() {
        blockService.createGenesisBlock();
        return JSON.toJSONString(blockCache.getBlockChain());
    }

    /**
     * 工作量证明PoW
     * 挖矿生成新的区块
     */
    @GetMapping("/create")
    @ResponseBody
    public String createNewBlock() {
        blockService.mine();
        return JSON.toJSONString(blockCache.getBlockChain());
    }
}
